package com.imooc.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * @author : 浦希成
 * @date : 2018/8/3 13:11
 */
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {
    /**
     * 默认请求时间是1秒，超过1秒便会触发降级
     * @return 字符串
     */

/*    @HystrixCommand(fallbackMethod = "fallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })*/

    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//设置熔断
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")
    })
    //这些配置可以写到配置文件汇总

    @GetMapping("/getProductInfoList")
    public String getProductInfoList(@RequestParam Integer number){
        if (number%2==0){
            return "success";
        }
        RestTemplate restTemplate=new RestTemplate();
        return restTemplate.postForObject("http://localhost:8001/product/listForOrder",
                Arrays.asList("12312312312312321"),
                String.class);
    }
    private String fallback(){

        return "太拥挤了，请稍后再试";
    }
    private String defaultFallback(){

        return "太拥挤了，请稍后再试··· ";
    }
}
